package sc.udp.impl;

import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import org.apache.log4j.Logger;

import sc.helper.Constants;
import sc.tcp.TCPGateway;
import sc.udp.UDPGateway;

public class UDPGatewayImpl implements UDPGateway {

	private Logger logger = Logger.getLogger(this.getClass());
	
	private DatagramSocket[] socket;

	private TCPGateway tcpGW;
	
	public UDPGatewayImpl(TCPGateway tcpGW) {
		this.tcpGW = tcpGW;
		socket = new DatagramSocket[2];
		
		try {
			socket[0] = new DatagramSocket(null);
			socket[0].setReuseAddress(true);
			socket[0].bind(new InetSocketAddress(Constants.UDP_RECEIVE_HOST, Constants.UDP_LISTEN_PORT));
			logger.debug("Socket bound to port: " + Constants.UDP_LISTEN_PORT);

			socket[1] = new DatagramSocket(null);
			socket[1].setReuseAddress(true);
			socket[1].bind(new InetSocketAddress(Constants.UDP_RECEIVE_HOST, Constants.UDP_GAME_PORT));
			logger.debug("Socket bound to port: " + Constants.UDP_GAME_PORT);
		
		} catch (SocketException e) {
			e.printStackTrace();
		}
				
		logger.debug("Starting UDPReceiver...");
		Thread receiver1 = new Thread(new UDPReceiver(this, tcpGW, Constants.UDP_LISTEN_PORT));
		Thread receiver2 = new Thread(new UDPReceiver(this, tcpGW, Constants.UDP_GAME_PORT));
		tcpGW.startTCPGateway(this);
		receiver1.start();
		receiver2.start();
	}
	
	public synchronized DatagramSocket getSocket(int port) {
		DatagramSocket soc = null;
		if (port == Constants.UDP_LISTEN_PORT) {
			soc = socket[0];
		} else if (port == Constants.UDP_GAME_PORT) {
			soc = socket[1];
		}
		return soc;
	}
	
	public synchronized TCPGateway getTCPGateway() {
		return tcpGW;
	}
}
